package com.wiiss.ams.util.http;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

public class HttpUtil {

    static {
        HttpRequest.setGlobalTimeout(60_000);
    }

    /**
     * hutool HttpRequest 不能直接动态定义http method 所以...
     * @author 52291590 2022年11月28日 上午10:27:50
     */
    public static HttpResponse request(com.wiiss.ams.util.http.HttpRequest httpRequest) {
        HttpRequest req = (switch (httpRequest.getMethod()) {
        case GET -> HttpRequest.get(httpRequest.getUrl());
        case POST -> HttpRequest.post(httpRequest.getUrl());
        case PUT -> HttpRequest.put(httpRequest.getUrl());
        case DELETE -> HttpRequest.delete(httpRequest.getUrl());
        default -> throw new IllegalArgumentException("Unexpected http method : " + httpRequest.getMethod());
        }).headerMap(httpRequest.getHeaderMap(), true);

        if (httpRequest.getData() != null && httpRequest.getHeaderMap().get(Header.CONTENT_TYPE.getValue()) != null
                && httpRequest.getHeaderMap().get(Header.CONTENT_TYPE.getValue()).contains(ContentType.JSON.getValue())) {
            req.body(httpRequest.getData().toString());
        } else {
            req.form(httpRequest.getData());
        }

        return req.execute();
    }

    private HttpUtil() {
        super();
    }

}
